package ltd.hxya.novel.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.hxya.novel.common.bean.UserBean;
import ltd.hxya.novel.user.entity.UserReadHistory;
import ltd.hxya.novel.user.feign.BookFeignService;
import ltd.hxya.novel.user.interceptor.UserLoginInterceptor;
import ltd.hxya.novel.user.mapper.UserReadHistoryMapper;
import ltd.hxya.novel.user.service.IUserReadHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * 用户阅读记录表 服务实现类
 * </p>
 *
 * @author hxya
 * @since 2022-09-13
 */
@Service
public class UserReadHistoryServiceImpl extends ServiceImpl<UserReadHistoryMapper, UserReadHistory> implements IUserReadHistoryService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BookFeignService bookFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 通过bookId和上次阅读的目录id，修改阅读历史表
     * @param bookId
     * @param indexId
     */
    @Override
    public void updateReadHistory(String bookId, String indexId) {
        UserBean userBean = UserLoginInterceptor.threadLocal.get();
        UpdateWrapper<UserReadHistory> userReadHistoryUpdateWrapper = new UpdateWrapper<>();
        userReadHistoryUpdateWrapper.eq("user_id",userBean.getId()).eq("book_id",bookId);
        UserReadHistory userReadHistory = new UserReadHistory();
        userReadHistory.setUserId(userBean.getId());
        userReadHistory.setBookId(bookId);
        userReadHistory.setPreContentId(indexId);
        userReadHistory.setUpdateTime(LocalDateTime.now());
        int total = this.baseMapper.update(userReadHistory, userReadHistoryUpdateWrapper);
        if (total==0){
            userReadHistory.setCreateTime(LocalDateTime.now());
            userReadHistory.setUpdateTime(LocalDateTime.now());
            this.save(userReadHistory);
        }

    }

    @Override
    public UserReadHistory lastReadIndex(String bookId) {

        //将bookIndex中的信息查询出来，并封装

        QueryWrapper<UserReadHistory> readHistoryQueryWrapper = new QueryWrapper<>();
        UserBean userBean = UserLoginInterceptor.threadLocal.get();
        String userId = userBean.getId();
        readHistoryQueryWrapper.eq("user_id",userId);
        readHistoryQueryWrapper.eq("book_id",bookId);
        UserReadHistory userReadHistory = this.baseMapper.selectOne(readHistoryQueryWrapper);
        //如果返回空，这说明没有读过这本书

        return userReadHistory;
    }
}
